
package org.itboys.mobile.service;

import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.*;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.TianJieWallet;
import org.itboys.mobile.entity.mysql.TianJieWalletBlockRecord;
import org.itboys.mobile.entity.mysql.TianJieWalletRecord;
import org.itboys.mobile.service.mongo.web.TianJieMemberService;
import org.itboys.mobile.util.DatetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_项目自动任务_权限。
 *
 */

@Service
public class SundayJobServiceOld {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private TianJieWalletMapper walletMapper;
	@Autowired
	private TianJieWalletReleaseRecordMapper releaseRecordMapper;
	@Autowired
	private TianJieWalletRecordMapper walletRecordMapper;
	@Autowired
	private TianJieWalletBlockMapper walletBlockMapper;
	@Autowired
	private TianJieWalletBlockRecordMapper walletBlockRecordMapper;
	@Autowired
	private SystemDictionaryService dictionaryService;
	@Autowired
	private TianJieMemberService memberService;
	/**
	 * 区块链自动根据买入记录卖出
	 */
	@Transactional
	public void autoSaleBlock(){

		//查询：未生成卖出的，区块链买入记录，需要匹配是否到自动卖出时间
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("type",SundayCommonConstants.block_record_type_buy);
		param.put("isSale",SundayCommonConstants.NO);
		param.put("status",SundayCommonConstants.block_record_status_done);
		List<TianJieWalletBlockRecord> buyRecords= walletBlockRecordMapper.select(param);

		//需要生成卖出的买入记录
		List<TianJieWalletBlockRecord> needToSaleRecords = new ArrayList<>();
		//区块链自动卖出天数
		SystemDictionary blockSaleDayDic = dictionaryService.getDictionaryByKey2("blockSaleDay");
		Integer blockSaleDay=Integer.valueOf(blockSaleDayDic.getValue());//
		//long blockSaleTime =
		Calendar now = Calendar.getInstance();

		for(TianJieWalletBlockRecord buyRecord:buyRecords){
			Calendar expectSaleDay = Calendar.getInstance();
			expectSaleDay.setTime(buyRecord.getCt());
			//叫上强制卖出的时间
			expectSaleDay.add(Calendar.DAY_OF_YEAR,blockSaleDay);
			if(expectSaleDay.getTimeInMillis()<=now.getTimeInMillis()){
				needToSaleRecords.add(buyRecord);
			}
		}
		if(ListUtil.isNull(needToSaleRecords))return;
		//获取用户信息，匹配比特币地址
		List<Long> memberIds = new ArrayList<>();
		for(TianJieWalletBlockRecord needToSaleRecord:needToSaleRecords){
			memberIds.add(needToSaleRecord.getMemberId());
		}
		if(ListUtil.isNull(memberIds))return;
		param.clear();
		param.put("id in",memberIds);
		List<TianJieMember> members =memberService.list(param);
		for(TianJieWalletBlockRecord needToSaleRecord:needToSaleRecords){
			//修改买入记录的状态
			needToSaleRecord.setIsSale(SundayCommonConstants.YES);
			String bitAddress="";
			for(TianJieMember member:members){
				if(LongUtil.isNotZreo(needToSaleRecord.getMemberId())&&
						needToSaleRecord.getMemberId().doubleValue()==member.getId()){
					bitAddress=member.getFinanceBitAddress();
					break;
				}
			}
			TianJieWalletBlockRecord saleRecord = new TianJieWalletBlockRecord(needToSaleRecord.getMemberId(),needToSaleRecord.getBlockWalletId(),
					needToSaleRecord.getTotalAmount(),needToSaleRecord.getAmount(),needToSaleRecord.getBlockNumber(),
					null,SundayCommonConstants.block_record_type_sale,
					SundayCommonConstants.block_record_status_doing, "系统自动卖出");
			saleRecord.setBitAddress(bitAddress);
			//新增卖出记录
			walletBlockRecordMapper.insert(saleRecord);
			//修改买入记录
			walletBlockRecordMapper.update(needToSaleRecord);
		}
	}
	/**
	 * 释放待释放金额，凌晨3点
	 */
	@Transactional
	public void release(){
		//按释放时间查询所有未释放的充值记录
	//	Date now = new Date();
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("status",SundayCommonConstants.YES);
		param.put("isRelease",SundayCommonConstants.NO);
		param.put("type",SundayCommonConstants.wallet_record_type_charge);
		param.put("releaseTimSmaller", DatetUtil.formatDateToTime(Calendar.getInstance().getTime()));
		//需要释放的钱包交易(充值)记录
		List<TianJieWalletRecord> needToReleaseRecords=  walletRecordMapper.select(param);
		if(ListUtil.isNull(needToReleaseRecords))return;
		//匹配对应的钱包
		List<Long> walletIds = new ArrayList<>();
		for(TianJieWalletRecord needToReleaseRecord:needToReleaseRecords){
			walletIds.add(needToReleaseRecord.getWalletId());
		}
		if(ListUtil.isNull(walletIds))return;
		param.clear();
		param.put("ids",walletIds);
		List<TianJieWallet> wallets = walletMapper.select(param);
		/**
		 * 2017年12月14日，
		 * 如果账户持有的待释放余额小于充值记录中的金额，只释放
		 */
		BigDecimal zero = new BigDecimal("0.00");
		for(TianJieWalletRecord needToReleaseRecord:needToReleaseRecords){
			logger.info("当前充值记录ID-==="+needToReleaseRecord.getId());
			//比较释放记录对应的钱包，如果待释放记录不足。跳过
			boolean isRelease=true;

			for(TianJieWallet wallet:wallets){
				if(LongUtil.isNotZreo(needToReleaseRecord.getWalletId())&&
						needToReleaseRecord.getWalletId()==wallet.getId().longValue()){
					//查询用户待释放金额是否还有钱
					if(wallet.getUnreleaseAmount().compareTo(zero)==1){
						isRelease=true;
						//待释放金额充足，按充值金额释放
						if(needToReleaseRecord.getAmount().compareTo(wallet.getUnreleaseAmount())!=1){
							//
							wallet.setUnreleaseAmount(wallet.getUnreleaseAmount().subtract(needToReleaseRecord.getAmount()));
							wallet.setReleaseAmount(wallet.getReleaseAmount().add(needToReleaseRecord.getAmount()));
							//待释放金额不足，按剩余待释放余额释放
						}else{
							//扣减钱包待释放
							wallet.setUnreleaseAmount(zero);
							//增加已释放金额
							wallet.setReleaseAmount(wallet.getReleaseAmount().add(wallet.getUnreleaseAmount()));
						}
						walletMapper.update(wallet);
					}


					break;
				}
			}
			if(isRelease){
				//修改充值记录
				needToReleaseRecord.setIsRelease(SundayCommonConstants.YES);
				logger.info("-----修改的待释放记录"+needToReleaseRecord.getId()+"计划释放时间="+DatetUtil.formatDateToTime(needToReleaseRecord.getReleaseTime()));
				walletRecordMapper.update(needToReleaseRecord);
				//新增钱包交易记录
				walletRecordMapper.insert(new TianJieWalletRecord(needToReleaseRecord.getMemberId(), needToReleaseRecord.getWalletId(), SundayCommonConstants.wallet_record_type_release, "待释放金额释放",needToReleaseRecord.getAbleAmount(), needToReleaseRecord.getAmount(), SundayCommonConstants.YES));
			}
		}
	}
}